<template>
	<el-cascader
		v-model="active"
		:options="treeData"
		:props="{
			value: 'id',
			label: 'name',
			checkStrictly: true
		}"
		clearable
		value="id"
		label="name"
		@change="onChange"
	></el-cascader>
</template>
<script>
    import { createTree } from '../../../../../utils/jk/jk-tool';

    export default {
        model: {
            prop: 'value',
            event: 'change'
        },
        props: {
            value: {
                type: [Number, String],
                default: null
            },
            optionList: {
                type: Array,
                default() {
                    return [];
                }
            }
        },
        data() {
            return {
                active: null,
                treeData: [],
                rawData: []
            };
        },
        methods: {
            onChange(e) {
                let item = {};
                if (e && e.length) {
                    item = this.rawData.find(x => x.id === e[e.length - 1]) || {};
                }
                this.$emit('change', item.id, item);
            }
        },
        watch: {
            optionList: {
                handler(newVal) {
                    const arr = newVal ? JSON.parse(JSON.stringify(newVal)) : [];
                    this.rawData = JSON.parse(JSON.stringify(arr));
                    this.treeData = createTree(arr, {}, 'parentId');
                },
                deep: true,
                immediate: true
            },
            value: {
                handler(newVal) {
                    this.active = newVal;
                },
                deep: true,
                immediate: true
            }
        }
    };
</script>
